<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>浏览器精确定位</title>
    <link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <style>
        html,body,#container{
            height:100%;
        }
        .info{
            width:26rem;
        }
    </style>
<body>
<div id='container'></div>
<div class="info">
    <h4 id='status'></h4><hr>
    <p id='result'></p><hr>
    <p >由于众多浏览器已不再支持非安全域的定位请求，为保位成功率和精度，请升级您的站点到HTTPS。</p>
</div>
<div id="myPageTop" style="opacity:0.8;display:none;">
    <table>
        <tr>
            <td>
                <label>请输入关键字：</label>
            </td>
        </tr>
        <tr>
            <td>
                <input id="tipinput" placeholder="请输入地址关键字" type="text"/>
                <input id="radius_input" placeholder="请输入覆盖范围" type="text" value="10" redius="10" />米
            </td>
        </tr>
        <tr>
            <td>
                <label id="map-center"></label>
                <input type="button" id="json_str" value="json"/>
            </td>
        </tr>
    </table>
</div>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.13&key=b3d347ea63d8ac4e07bc3915f0123669&plugin=AMap.Autocomplete,AMap.PlaceSearch,AMap.MouseTool"></script>
<script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<script type="text/javascript" src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<!-- UI组件库 1.0 -->
<script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
<script type="text/javascript">
 
    var map = new AMap.Map('container', {
        resizeEnable: true
    });
    init();
    search();
 
    var circleList = [];
    var markerList = [];
 
 
    map.on('click', function(e) {
        var center = new AMap.LngLat(e.lnglat.getLng(),e.lnglat.getLat());
        marker(center);
    });
    //为地图注册click事件获取鼠标点击出的经纬度坐标
    map.on('mousemove', function(e) {
        $("#map-center").text(e.lnglat.getLng() + ',' + e.lnglat.getLat()+","+map.getZoom());
    });
 
    $("#json_str").on('click', function(e) {
        var jsonList = [];
        for (var i=0;i<circleList.length;i++){
            var jsonMap = {};
            var center = circleList[i].getCenter();
            jsonMap['lng'] = center.getLng();
            jsonMap['lat'] = center.getLat();
            jsonMap['zoom'] = map.getZoom();
            jsonMap['radius'] = circleList[i].getRadius();
            jsonList.push(jsonMap);
        }
        var json = JSON.stringify(jsonList);
        console.log(json);
        alert(json);
    });
 
 
    $("#radius_input").on("input propertychange change",function(){
        var $radius_input = $("#radius_input").val();
        if(!isNaN($radius_input)){
            $radius_input = parseInt($radius_input);
        }else{
            $radius_input = parseInt($("#radius_input").attr("redius"));
        }
        for(var i=0;i<circleList.length;i++){
            circleList[i].setRadius($radius_input);
        }
 
    });
 
    //延迟执行
    setTimeout(function(){
        $(".info").hide();
        $("#myPageTop").show();
    },2000);
 
 
    //初始化自身定位
    function init() {
        AMap.plugin('AMap.Geolocation', function() {
            var geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：5s
                buttonPosition:'RB',    //定位按钮的停靠位置
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
 
            });
            map.addControl(geolocation);
            geolocation.getCurrentPosition(function(status,result){
                if(status=='complete'){
                    onComplete(result)
                }else{
                    onError(result)
                }
            });
        });
    }
 
    //文本检索
    function search() {
        //输入提示
        var autoOptions = {
            input: "tipinput"
        };
        var auto = new AMap.Autocomplete(autoOptions);
        var placeSearch = new AMap.PlaceSearch({
            map: map
        });  //构造地点查询类
        AMap.event.addListener(auto, "select", select);//注册监听，当选中某条记录时会触发
        function select(e) {
            placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);  //关键字查询查询
        }
    }
    //解析定位结果
    function onComplete(data) {
        document.getElementById('status').innerHTML='定位成功'
        var str = [];
        str.push('定位结果：' + data.position);
        str.push('定位类别：' + data.location_type);
        if(data.accuracy){
            str.push('精度：' + data.accuracy + ' 米');
        }//如为IP精确定位结果则没有精度信息
        str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
        document.getElementById('result').innerHTML = str.join('<br>');
    }
    //解析定位错误信息
    function onError(data) {
        document.getElementById('status').innerHTML='定位失败'
        document.getElementById('result').innerHTML = '失败原因排查信息:'+data.message;
    }
 
    //圆圆
    function circle_init(center) {
        var $radius_input = $("#radius_input").val();
        if(!isNaN($radius_input)){
            $radius_input = parseInt($radius_input);
        }else{
            $radius_input = parseInt($("#radius_input").attr("redius"));
        }
 
        //创建 画圆
        var circle = new AMap.Circle({
            center: center, // 圆心位置
            radius: $radius_input,  //半径
            strokeColor: "#6A75F5",  //线颜色
            strokeOpacity: 1,  //线透明度
            strokeWeight: 1,  //线粗细度
            fillColor: "#00C2FF",  //填充颜色
            fillOpacity: 0.2 //填充透明度
        });
        map.add(circle);
        circleList.push(circle);
    }
 
    //标点画圆
    function marker(center) {
        //icon的取值请见  http://fontawesome.io/icons/
        AMapUI.loadUI(['overlay/AwesomeMarker', 'overlay/SimpleMarker'],
            function(AwesomeMarker, SimpleMarker) {
                var iconStyles = SimpleMarker.getBuiltInIconStyles();
 
                // 构造点标记
                // var marker = new AMap.Marker({
                //     position: center,
                //     draggable: true,
                //     cursor: 'move',
                // });
                var marker = new AwesomeMarker({
 
                    //设置awesomeIcon
                    awesomeIcon: 'arrows',
                    iconLabel: {
                        style: {
                            color: "#fff",
                            fontSize: '14px'
                        }
                    },
 
                    //图标
                    iconStyle: iconStyles[2],
                    draggable: true,
                    position: center,
                });
                map.add(marker);
                markerList.push(marker);
 
                marker.on('dragend', function () {
                    //拖动结束画圆
                    circle_init(marker.getPosition());
                });
 
                marker.on('dragstart', function () {
                    var getCenter = marker.getPosition();
                    for(var i=0;i<circleList.length;i++){
                        if(circleList[i].getCenter()==getCenter){
                            map.remove(circleList[i]);
                            circleList.splice(i,1);
                        }
                    }
 
                });
 
                marker.on('rightclick', function () {
                    var getCenter = marker.getPosition();
                    for(var i=0;i<circleList.length;i++){
                        if(circleList[i].getCenter()==getCenter){
                            map.remove(circleList[i]);
                            map.remove(marker);
                            circleList.splice(i,1);
                        }
                    }
                });
 
                // 构造矢量圆形
                circle_init(center);
            });
    }
 
    var logMapinfo = function (){
        var zoom = map.getZoom(); //获取当前地图级别
        var center = map.getCenter(); //获取当前地图级别
        $("#map-center").text(center.toString());
    };
 
</script>
</body>
</html>